package com.lin.linojcodesandbox.utils;

import com.lin.linojcodesandbox.codesandbox.model.ExecuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 进程工具类
 */
public class ProcessUtils {

    public static ExecuteMessage runProcessAndGetMessage(Process process,String exeCommand){
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            // 等待程序执行 获取错误码
            int exitValue = process.waitFor();
            executeMessage.setExitValue(exitValue);
            if(exitValue==0){
                //正常退出
                System.out.println(exeCommand + "成功");
                //分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder successStringBuilder = new StringBuilder();
                //逐行读取
                String successMessage;
                while((successMessage = bufferedReader.readLine()) != null){
                    successStringBuilder.append(successMessage);
                }
                executeMessage.setMessage(successStringBuilder.toString());//添加执行信息
            }else{
                //异常退出
                System.out.println(exeCommand + "失败");
                //分批获取进程的正常输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder errorStringBuilder = new StringBuilder();
                //逐行读取
                String errorMessage;
                while((errorMessage = errorBufferedReader.readLine()) != null){
                    errorStringBuilder.append(errorMessage).append('\n');
                }
                executeMessage.setErrorMessage(errorStringBuilder.toString());//添加异常执行信息
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return executeMessage;
    }
}
